package com.lwj.test.thread.demo1;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/***************************************************************************
 *<PRE>
 *  Project Name    : 
 *
 *  Package Name    : 
 *
 *  File Name       : ConsumeProducer.java
 *
 *  Creation Date   : 
 *
 *  Author          : Frank
 *
 *  Purpose         : 
 *
 *
 *  History         : 
 *
 *</PRE>
 ***************************************************************************/
public class ConsumeProducer {

	//任务链表
	private ArrayList<IProductWorker> taskList = new ArrayList<IProductWorker>();
	
	//停止消费者线程标识
	private boolean blStop = false; 
	
	/**
	 * 消费者线程
	 */
	private Thread thread = new Thread()
	{

		@Override
		public void run() {
			while(!isEmpty()||!isBlStop())
			{
				consumeProduct();
			}
		}
		
	};
	
	/**
	 * 默认构造函数
	 */
	public ConsumeProducer() {
		thread.setName("Consume-Thread-"+this.toString().split("@")[1]);
		thread.start();
	}

	/**
	 * 带线程名的构造函数
	 * @param threadName
	 */
	public ConsumeProducer(String threadName) {
		thread.setName(threadName+"-"+this.toString().split("@")[1].substring(6));
		thread.start();
	}
	
	/*
	 * 
	 * @return
	 */
	private boolean isBlStop() {
		return blStop;
	}

	/**
	 * 
	 * @param blStop
	 */
	public void setBlStop(boolean blStop) {
		this.blStop = blStop;
	}


	/**
	 * 生产者函数，将IProductWorker对象放入生产消费链表中，唤醒消费者。
	 * @param product
	 */
	public void createProduct(IProductWorker product)
	{
		synchronized (taskList) {
			
			taskList.add(product);
			
			taskList.notify();
		}
	}
	
	/**
	 * 
	 * @return
	 */
	public boolean isEmpty()
	{
		synchronized (taskList) {
			return taskList.isEmpty();
		}
	}
	
	/**
	 * 消费者从生产消费链表中获取IProductWorker对象，回调对象的doWork函数。
	 */
	@SuppressWarnings("unchecked")
	public void consumeProduct()
	{
		synchronized (taskList) {
			if(taskList.isEmpty()&&!isBlStop())
			{
				try {
					taskList.wait();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
			
			IProductWorker product = null;
			List<IProductWorker> temp = (List<IProductWorker>) (taskList).clone();
			
			Iterator<IProductWorker> iter = (Iterator<IProductWorker>) temp.iterator();
			
			while(iter.hasNext())
			{
				product = (IProductWorker)iter.next();
				product.doWork();
				taskList.remove(product);
			}
			
		}
	}

}
